<template>
  <div class="textarea_cont">
    <textarea
      ref="textareaRef"
      class="next-cont-textarea"
      v-model="value"
      :rows="rows"
      :placeholder="placeholder"
      :disabled="disabled"
      :maxlength="maxlength"
      :autofocus="autofocus"
      :readonly="readonly"
      :style="style"
      @input="updateValue"
    ></textarea>
    <div class="char_count">{{ value?.length }}/{{ maxlength }}</div>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
/*
rows: 文本区域显示的行数，默认为3。
placeholder: 占位符文本。
disabled: 是否禁用文本区域，默认为false。
maxlength: 最大输入长度限制。
autofocus: 是否自动聚焦到文本区域，默认为false。
readonly: 是否只读，默认为false。
style: 自定义样式对象。
*/
const props = defineProps({
  modelValue: {
    type: String,
    default: "",
  },
  rows: {
    type: Number,
    default: 3,
  },
  placeholder: {
    type: String,
    default: "请输入",
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  maxlength: {
    type: String,
    default: "500",
  },
  autofocus: {
    type: Boolean,
    default: false,
  },
  readonly: {
    type: Boolean,
    default: false,
  },
  style: {
    type: Object as any,
    default: () => {},
  },
});
const emits = defineEmits(["update:modelValue"]);
const value = ref<string>("");
const textareaRef = ref<any>();
function updateValue(val: any) {
  emits("update:modelValue", value.value);
  adjustHeight(val.target);
}
function adjustHeight(textarea: any) {
  textarea.style.height = `inherit`;
  textarea.style.height = `${textarea.scrollHeight}px`;
}
</script>

<style lang="scss" scoped>
.textarea_cont {
  width: 100%;
  position: relative;
  .next-cont-textarea {
    width: 100%;
    border: 1px solid #ccc;
    border-radius: 4px;
    padding: 4px;
    min-height: 100px;
    color: #606266;
    font-size: 14px;
    overflow-y: hidden;
  }
  .next-cont-textarea:focus {
    outline: none;
  }
  .char_count {
    position: absolute;
    bottom: 10px;
    right: 10px;
    font-size: 12px;
    color: #999;
  }
}
</style>
